<template>
  <div class="carbon-platform">
    <!-- 导航栏 - 参考About.vue的导航结构 -->
    <nav class="navbar sticky-top bg-white shadow-sm py-3">
      <div class="container">
        <div class="d-flex justify-content-between align-items-center w-100">
          <!-- 网站标志 -->
          <div class="navbar-logo">
            <span class="logo-icon">🌱</span>
            <span class="logo-text">绿碳平台</span>
          </div>

          <!-- 中间导航链接 - 桌面版 -->
          <ul class="navbar-nav list-unstyled d-flex flex-row gap-3 gap-lg-5 justify-content-center flex-wrap align-items-center mb-0 fw-bold flex-grow-1 mx-4">
            <li class="nav-item">
              <a href="/index" class="nav-link text-dark hover:text-primary transition-colors">首页</a>
            </li>
            <li class="nav-item">
              <a href="/shop" class="nav-link text-dark hover:text-primary transition-colors">碳积分市场</a>
            </li>
            <li class="nav-item">
              <a href="/blog" class="nav-link text-dark hover:text-primary transition-colors">博客</a>
            </li>
            <li class="nav-item">
              <a href="/contact" class="nav-link text-dark hover:text-primary transition-colors">联系我们</a>
            </li>
            <li class="nav-item">
              <a href="/about" class="nav-link text-dark hover:text-primary transition-colors">关于我们</a>
            </li>
            <li class="nav-item">
              <a href="/order" class="nav-link text-dark hover:text-primary transition-colors">我的订单</a>
            </li>
          </ul>

          <!-- 右侧功能区 - 使用emoji图标 -->
          <div class="d-flex align-items-center gap-4 gap-lg-5">
            <!-- 搜索按钮 -->
            <button class="btn p-2 text-dark hover:text-primary transition-colors" aria-label="搜索">
              <span class="fs-5">🔍</span>
            </button>

            <!-- 购物车 -->
            <a href="/cart" class="btn p-2 text-dark hover:text-primary transition-colors position-relative" aria-label="购物车">
              <span class="fs-5">🛒</span>
            </a>

            <!-- 用户菜单 -->
            <div class="dropdown">
              <button class="btn p-2 text-dark hover:text-primary transition-colors" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="用户菜单">
                <span class="fs-5">👤</span>
              </button>
              <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="/login">登录</a></li>
                <li><a class="dropdown-item" href="/register">注册</a></li>
                <li><a class="dropdown-item" href="/account">我的账户</a></li>
              </ul>
            </div>

            <!-- 移动端菜单按钮 -->
            <button class="btn d-lg-none p-2 text-dark" type="button" data-bs-toggle="offcanvas" data-bs-target="#mobileMenu" aria-label="菜单">
              <span class="fs-5">☰</span>
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 顶部横幅 -->
    <div class="banner-section">
      <div class="container">
        <div class="banner-content">
          <h1 class="banner-title">我的交易订单</h1>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <main class="orders-page py-5">
      <div class="container-lg">
        <!-- 订单筛选区 -->
        <section class="filters-section mb-5 bg-light p-4 rounded shadow-sm">
          <div class="row g-3 align-items-center">
            <div class="col-md-3">
              <select class="form-select" v-model="selectedStatus">
                <option value="all">全部状态</option>
                <option value="pending">待确认</option>
                <option value="processing">处理中</option>
                <option value="completed">已完成</option>
                <option value="cancelled">已取消</option>
              </select>
            </div>
            <div class="col-md-3">
              <select class="form-select" v-model="selectedType">
                <option value="all">全部类型</option>
                <option value="buy">买入</option>
                <option value="sell">卖出</option>
              </select>
            </div>
            <div class="col-md-4">
              <div class="input-group">
                <input type="date" class="form-control" v-model="startDate">
                <span class="input-group-text">至</span>
                <input type="date" class="form-control" v-model="endDate">
              </div>
            </div>
            <div class="col-md-2">
              <button class="btn btn-primary w-100" @click="filterOrders">筛选</button>
            </div>
          </div>
        </section>

        <!-- 订单列表 -->
        <section class="orders-list mb-5">
          <div class="card shadow-sm">
            <div class="table-responsive">
              <table class="table table-hover mb-0">
                <thead class="table-light">
                <tr>
                  <th>订单编号</th>
                  <th>交易类型</th>
                  <th>项目名称</th>
                  <th>数量(吨CO₂e)</th>
                  <th>单价(元)</th>
                  <th>总金额(元)</th>
                  <th>状态</th>
                  <th>创建时间</th>
                  <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="order in filteredOrders" :key="order.oid">
                  <td>{{ order.orderNo || order.oid }}</td>
                  <td>
                      <span class="badge" :class="order.orderType === 'BUY' ? 'bg-primary' : 'bg-success'">
                        {{ order.orderType === 'BUY' ? '买入' : '卖出' }}
                      </span>
                  </td>
                  <td>{{ order.factoryName || '碳积分商品' }}</td>
                  <td>{{ order.quantity || 0 }}</td>
                  <td>{{ order.unitPrice || 0 }}</td>
                  <td>{{ order.totalPrice || 0 }}</td>
                  <td>
                      <span class="badge" :class="getStatusClass(order.status)">
                        {{ getStatusText(order.status) }}
                      </span>
                  </td>
                  <td>{{ formatDate(order.createdAt || order.createTime) }}</td>
                  <td>
                    <button class="btn btn-sm btn-outline-primary me-2" @click="viewOrderDetail(order.oid)">详情</button>
                    <button
                        class="btn btn-sm btn-outline-danger"
                        @click="cancelOrder(order.oid)"
                        v-if="order.status === 'PENDING'">
                      取消
                    </button>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
            <div class="card-footer text-center" v-if="filteredOrders.length === 0">
              暂无符合条件的订单
            </div>
          </div>
        </section>

        <!-- 分页 -->
        <div class="d-flex justify-content-center">
          <nav aria-label="Page navigation">
            <ul class="pagination">
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <a class="page-link" href="#" @click.prevent="changePage(currentPage - 1)">上一页</a>
              </li>
              <li class="page-item" :class="{ active: page === currentPage }" v-for="page in totalPages" :key="page">
                <a class="page-link" href="#" @click.prevent="changePage(page)">{{ page }}</a>
              </li>
              <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                <a class="page-link" href="#" @click.prevent="changePage(currentPage + 1)">下一页</a>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </main>

    <!-- 页脚部分 - 参考About.vue的页脚 -->
    <footer class="main-footer">
      <div class="container">
        <div class="footer-bottom">
          <p class="copyright">© 2025 绿碳平台 版权所有 | 京ICP备12345678号</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script>
import { orderApi } from '../api/index.js'

export default {
  name: 'Orders',
  data() {
    return {
      // 筛选条件
      selectedStatus: 'all',
      selectedType: 'all',
      startDate: '',
      endDate: '',

      // 分页相关
      currentPage: 1,
      pageSize: 10,

      // 订单数据
      orders: [],
      currentUserId: null, // 当前用户ID
      isLoading: false
    }
  },
  computed: {
    // 筛选后的订单
    filteredOrders() {
      return this.orders.filter(order => {
        // 状态筛选
        if (this.selectedStatus !== 'all' && order.status !== this.selectedStatus) {
          return false;
        }

        // 类型筛选
        if (this.selectedType !== 'all' && order.type !== this.selectedType) {
          return false;
        }

        // 日期筛选
        const orderDate = new Date(order.createdAt).toISOString().split('T')[0];
        if (this.startDate && orderDate < this.startDate) {
          return false;
        }
        if (this.endDate && orderDate > this.endDate) {
          return false;
        }

        return true;
      });
    },

    // 总页数
    totalPages() {
      return Math.ceil(this.filteredOrders.length / this.pageSize);
    },

    // 当前页显示的订单
    currentPageOrders() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      return this.filteredOrders.slice(startIndex, startIndex + this.pageSize);
    }
  },
  async mounted() {
    // 获取当前用户ID
    this.getCurrentUserId();
    // 加载订单数据
    await this.loadOrdersData();
  },
  methods: {
    // 获取当前用户ID（后端以业务主键 uid 查询）
    getCurrentUserId() {
      const currentUser = localStorage.getItem('currentUser');
      if (currentUser) {
        const userData = JSON.parse(currentUser);
        // 优先 uid，其次 id
        this.currentUserId = userData.uid || userData.id || 1;
      } else {
        this.currentUserId = 1;
      }
    },

    // 加载订单数据
    async loadOrdersData() {
      if (!this.currentUserId) return;
      
      this.isLoading = true;
      try {
        const response = await orderApi.getUserOrders(this.currentUserId);
        if (response.data && Array.isArray(response.data)) {
          // 将后端的 OrderDetailDto -> 前端展现模型
          this.orders = response.data.map((dto) => {
            const order = dto.order || {};
            const factory = dto.factory || {};
            const items = dto.orderItems || [];
            const unitPrice = items.length > 0 ? (items[0].pricePerUnit || 0) : 0;
            return {
              oid: order.oid,
              status: order.orderStatus,
              factoryName: factory.factoryName,
              quantity: order.qtyRequested,
              unitPrice: unitPrice,
              totalPrice: order.totalPrice,
              createdAt: order.createdAt,
              type: 'buy'
            };
          });
        } else {
          console.error('加载订单失败:', response);
          this.orders = [];
        }
      } catch (error) {
        console.error('加载订单失败:', error);
        this.orders = [];
      } finally {
        this.isLoading = false;
      }
    },

    // 筛选订单
    filterOrders() {
      this.currentPage = 1; // 重置到第一页
    },

    // 改变页码
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;
    },

    // 查看订单详情
    viewOrderDetail(id) {
      this.$router.push(`/order/${id}`);
    },

    // 取消订单
    async cancelOrder(id) {
      if (!confirm('确定要取消此订单吗？')) return;
      
      try {
        const response = await orderApi.cancelOrder(this.currentUserId, id);
        if (response.data && response.data.code === '1') {
          // 更新本地订单状态
          const order = this.orders.find(o => o.oid === id);
          if (order) {
            order.status = 'CANCELLED';
          }
          alert('订单取消成功');
        } else {
          alert('取消订单失败: ' + (response.data?.message || '未知错误'));
        }
      } catch (error) {
        console.error('取消订单失败:', error);
        alert('取消订单失败，请稍后重试');
      }
    },

    // 获取状态显示文本
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待确认',
        'PROCESSING': '处理中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消',
        'pending': '待确认',
        'processing': '处理中',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return statusMap[status] || status;
    },

    // 获取状态标签样式
    getStatusClass(status) {
      const classMap = {
        'PENDING': 'bg-warning text-dark',
        'PROCESSING': 'bg-info',
        'COMPLETED': 'bg-success',
        'CANCELLED': 'bg-secondary',
        'pending': 'bg-warning text-dark',
        'processing': 'bg-info',
        'completed': 'bg-success',
        'cancelled': 'bg-secondary'
      };
      return classMap[status] || 'bg-light text-dark';
    },

    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  }
}
</script>

<style scoped>
.carbon-platform {
  font-family: 'Nunito', sans-serif;
}

.banner-section {
  background-image: url('../../public/images/banner-1.jpg');
  background-size: cover;
  background-position: center;
  height: 300px;
  display: flex;
  align-items: center;
  position: relative;
}

.banner-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.2);
}

.banner-content {
  position: relative;
  z-index: 1;
  color: #fff;
  padding: 20px;
}

.banner-title {
  font-size: 3rem;
  font-weight: 700;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
  margin: 0;
}

@media (max-width: 768px) {
  .banner-section {
    height: 200px;
  }

  .banner-title {
    font-size: 2rem;
  }

  .table-responsive {
    font-size: 0.875rem;
  }

  .btn-sm {
    padding: 0.2rem 0.4rem;
    font-size: 0.75rem;
  }
}

.orders-page .table th,
.orders-page .table td {
  vertical-align: middle;
}

.pagination .page-item.active .page-link {
  background-color:#fff;
  border-color: #198754;
}

.pagination .page-link {
  color: #198754;
}

.pagination .page-link:hover {
  color: #146c43;
}
</style>